<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1200px"
      append-to-body
      center
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-card class="box-card" style="margin-bottom: 20px">
          <div slot="header" class="clearfix">
            <span>{{ $t("dedicated_contribution_plan") }}</span>
          </div>
          <el-form-item :label="$t('employer')" prop="employerId">
            <el-select
              v-model="form.employerId"
              :placeholder="$t('please_select', { name: $t('employer') })"
              @change="employerChange"
            >
              <el-option
                v-for="item of employerList"
                :key="item.id"
                :label="item.employerName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('plan_type')" prop="schemeType">
            <el-radio-group v-model="form.schemeType" @change="getPlanListChange()">
              <el-radio
                :label="dict.value"
                v-for="dict in dict.type.contribution_plan_type"
                :key="dict.value"
                >{{ dict.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item :label="$t('plan_name')" prop="schemeId">
            <el-select
              v-model="form.schemeId"
              filterable
              remote
              :placeholder="$t('please_enter_plan_name')"
              clearable
              reserve-keyword
              :remote-method="getPlanList"
              :loading="searchLoading"
              @change="schemeChange"
            >
              <el-option
                v-for="item in planList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-card>
        <el-card class="box-card" style="margin-bottom: 20px">
          <div slot="header" class="clearfix">
            <span>{{ $t("social_provident") }}</span>
          </div>
          <el-card class="box-card" style="margin-bottom: 20px">
            <div slot="header" class="clearfix">
              <span>{{ $t("social_insurance") }}</span>
            </div>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleAddSocialSecurityInfo"
                  >{{ $t("add") }}</el-button
                >
              </el-col>
            </el-row>
            <el-table :data="securityVOList" border :max-height="tableHeight">
              <el-table-column
                :label="$t('payment_location')"
                align="center"
                prop="city"
                width="150"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.city"
                    :placeholder="
                      $t('please_enter', { name: $t('payment_location') })
                    "
                  />
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('local_resident')"
                align="center"
                prop="isLocal"
                width="150"
              >
                <template slot-scope="scope">
                  <el-select
                    v-model="scope.row.isLocal"
                    :placeholder="
                      $t('please_select', { name: $t('local_resident') })
                    "
                  >
                    <el-option
                      v-for="dict in dict.type.yes_or_no"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('payment_base')"
                align="center"
                prop="paymentBase"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.paymentBase"
                    :placeholder="
                      $t('please_enter', { name: $t('payment_base') })
                    "
                  />
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('welfare_rank')"
                align="center"
                prop="grade"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.grade"
                    :placeholder="
                      $t('please_enter', { name: $t('welfare_rank') })
                    "
                  />
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('remarks')"
                align="center"
                prop="remark"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.remark"
                    :placeholder="$t('please_enter', { name: $t('remarks') })"
                  />
                </template>
              </el-table-column>
              <el-table-column :label="$t('action')" width="100">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    @click="handleDeleteSocialSecurityInfo(scope.$index)"
                    >{{ $t("delete") }}</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-card>

          <el-card class="box-card" style="margin-bottom: 20px">
            <div slot="header" class="clearfix">
              <span>{{ $t("housing_provident_fund") }}</span>
            </div>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleAddAccumulationInfo"
                  >{{ $t("add") }}</el-button
                >
              </el-col>
            </el-row>
            <el-table :data="fundVOList" border>
              <el-table-column
                :label="$t('payment_location')"
                align="center"
                prop="city"
                width="150"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.city"
                    :placeholder="
                      $t('please_enter', { name: $t('payment_location') })
                    "
                  />
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('payment_base')"
                align="center"
                prop="paymentBase"
                width="150"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.paymentBase"
                    :placeholder="
                      $t('please_enter', { name: $t('payment_base') })
                    "
                  />
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('personal_contribution_rate')"
                align="center"
                prop="individualProportion"
                width="150"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.individualProportion"
                    :placeholder="
                      $t('please_enter', {
                        name: $t('personal_contribution_rate'),
                      })
                    "
                  />
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('company_contribution_rate')"
                prop="unitProportion"
                align="center"
                width="150"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.unitProportion"
                    :placeholder="
                      $t('please_enter', {
                        name: $t('company_contribution_rate'),
                      })
                    "
                  />
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('remarks')"
                align="center"
                prop="remark"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.remark"
                    :placeholder="$t('please_enter', { name: $t('remarks') })"
                  />
                </template>
              </el-table-column>
              <el-table-column :label="$t('action')" align="center" width="100">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    @click="handleDeleteAccumulationInfo(scope.$index)"
                    >{{ $t("delete") }}</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-card>
          <el-card class="box-card" style="margin-bottom: 20px">
            <div slot="header" class="clearfix">
              <span>{{ $t("personal_income_tax") }}</span>
            </div>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleAddPersonalTaxInfo"
                  >{{ $t("add") }}</el-button
                >
              </el-col>
            </el-row>
            <el-table :data="taxVOList" border>
              <el-table-column
                :label="$t('special_additional_deduction')"
                align="center"
                prop="specialDeduction"
                width="150"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.specialDeduction"
                    :placeholder="
                      $t('please_enter', {
                        name: $t('special_additional_deduction'),
                      })
                    "
                  />
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('deduction_amount')"
                align="center"
                prop="deductionAmount"
                width="150"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.deductionAmount"
                    :placeholder="
                      $t('please_enter', {
                        name: $t('deduction_amount'),
                      })
                    "
                  />
                </template>
              </el-table-column>

              <el-table-column
                :label="$t('effective_date')"
                align="center"
                prop="dateDffective"
              >
                <template slot-scope="scope">
                  <el-date-picker
                    clearable
                    v-model="scope.row.dateDffective"
                    type="date"
                    value-format="yyyy-MM-dd"
                    :placeholder="
                      $t('please_select', {
                        name: $t('effective_date'),
                      })
                    "
                    style="width: 100%"
                  >
                  </el-date-picker>
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('expiry_date')"
                align="center"
                prop="dateExpiration"
              >
                <template slot-scope="scope">
                  <el-date-picker
                    clearable
                    v-model="scope.row.dateExpiration"
                    type="date"
                    value-format="yyyy-MM-dd"
                    :placeholder="
                      $t('please_select', {
                        name: $t('expiry_date'),
                      })
                    "
                    style="width: 100%"
                  >
                  </el-date-picker>
                </template>
              </el-table-column>
              <el-table-column :label="$t('status')" align="center" width="150">
                <template slot-scope="scope">
                  {{ getStatusText(scope.row) }}
                </template>
              </el-table-column>
              <el-table-column :label="$t('action')" align="center" width="100">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    @click="handleDeletePersonalTaxInfo(scope.$index)"
                    >{{ $t("delete") }}</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-card>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{
          $t("confirm")
        }}</el-button>
        <el-button @click="cancel">{{ $t("cancel") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { listScheme } from "@/api/custom/contributionPlan";
import { updatePlan, findEmployers } from "@/api/custom/employeeList";
export default {
  name: "Employee",
  dicts: ["contribution_plan_type", "yes_or_no"],
  components: {},
  data() {
    return {
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        schemeType: [
          {
            required: true,
            message: this.$t("cannot_empty", { name: this.$t("plan_type") }),
            trigger: "blur",
          },
        ],
        schemeId: [
          {
            required: true,
            message: this.$t("cannot_empty", { name: this.$t("plan_name") }),
            trigger: "blur",
          },
        ],
        employerId: [
          {
            required: true,
            message: this.$t("cannot_empty", { name: this.$t("employer") }),
            trigger: "blur",
          },
        ],
      },
      searchLoading: false,
      planList: [],
      //表格数据
      securityVOList: [],
      fundVOList: [],
      taxVOList: [],
      employerList: [],
      planListIndex: null,
    };
  },
  methods: {
    employerChange(val) {
      let find = this.employerList.find((item) => item.id == val);
      this.form.employerName = find.employerName;
      this.form.schemeId = null;
      this.form.schemeType = null;
    },
    schemeChange(val) {
      let find = this.planList.find((item) => item.value == val);
      this.$set(this.form, "schemeName", find.label);
      this.$forceUpdate()
    },
    findEmployers() {
      findEmployers(this.form.empId).then((res) => {
        this.employerList = res.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.securityVOList = [];
      this.fundVOList = [];
      this.taxVOList = [];
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    handlePlan(row, index) {
      this.form = row;
      this.planListIndex = index;
      this.securityVOList = this.form.securityDTOList || [];
      this.fundVOList = this.form.fundDTOList || [];
      this.taxVOList = this.form.taxDTOList || [];
      this.title = this.$t("dedicated_contribution_plan");
      this.open = true;
      this.getPlanList();
      this.findEmployers();
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.securityVOList = this.securityVOList;
          this.form.fundVOList = this.fundVOList;
          this.form.taxVOList = this.taxVOList;
          if (this.title === this.$t("modify")) {
            this.$emit("editPlan", this.form, this.planListIndex);
          } else {
            this.$emit("addPlan", this.form);
          }

          this.open = false;
          this.$modal.msgSuccess(this.$t("operation_successful"));
        }
      });
    },
    //新增社保信息表格
    handleAddSocialSecurityInfo() {
      let obj = {
        city: null,
        isLocal: null,
        paymentBase: null,
        grade: null,
        remark: null,
      };
      this.securityVOList.push(obj);
    },
    //删除社保信息
    handleDeleteSocialSecurityInfo(index) {
      this.securityVOList.splice(index, 1);
    },
    //新增公积金信息
    handleAddAccumulationInfo() {
      let obj = {
        city: null,
        paymentBase: null,
        individualProportion: null,
        unitProportion: null,
        remark: null,
      };
      this.fundVOList.push(obj);
    },
    //删除公积金信息
    handleDeleteAccumulationInfo(index) {
      this.fundVOList.splice(index, 1);
    },
    handleAddPersonalTaxInfo() {
      let obj = {
        specialDeduction: null,
        deductionAmount: null,
        dateDffective: null,
        dateExpiration: null,
      };
      this.taxVOList.push(obj);
    },
    handleDeletePersonalTaxInfo(index) {
      this.taxVOList.splice(index, 1);
    },
    getStatusText(row) {
      if (row.dateExpiration && row.dateDffective) {
        const newDataTime = new Date().getTime();
        const endDateTime = new Date(row.dateExpiration).getTime();
        const startDateTime = new Date(row.dateDffective).getTime();
        if (startDateTime > newDataTime) {
          return this.$t("not_effective");
        } else if (endDateTime > newDataTime) {
          return this.$t("in_effect");
        } else {
          return this.$t("expired");
        }
      } else {
        return "";
      }
    },
    getPlanList(searchValue) {
      if (!this.form.employerId) return;
      this.searchLoading = true;
      let queryParams = {
        pageNum: 1,
        pageSize: 100,
        employerId: this.form.employerId,
      };
      listScheme({
        ...queryParams,
        schemeName: searchValue,
        schemeType: this.form.schemeType,
      }).then((response) => {
        this.planList = response.data.records.map((item) => {
          return {
            label: item.schemeName,
            value: item.id,
          };
        });
        this.searchLoading = false;
      });
    },
    getPlanListChange(searchValue) {
      if (!this.form.employerId) return;
      this.form.schemeId = null;
      this.searchLoading = true;
      let queryParams = {
        pageNum: 1,
        pageSize: 100,
        employerId: this.form.employerId,
      };
      listScheme({
        ...queryParams,
        schemeName: searchValue,
        schemeType: this.form.schemeType,
      }).then((response) => {
        this.planList = response.data.records.map((item) => {
          return {
            label: item.schemeName,
            value: item.id,
          };
        });
        this.searchLoading = false;
      });
    },
  },
};
</script>
